package com.tbq.rebootapk;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import java.util.Date;

/**
 * Created by Administrator on 2015/7/23.
 * 检测塔百奇是否运行中
 */
public class CheckAppRunService extends Service{
    private boolean isFirst = true;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d("LongRunningService", "executed at " + new Date().toString());
//                Toast.makeText(getApplicationContext(), "qqqqq", 1000).show();
                handler.sendEmptyMessage(1);
                if(isFirst)
                {
                    Intent intent = getPackageManager().getLaunchIntentForPackage("com.tbq.tbqj_main"); //打开android自带的视频播放器为例
                    startActivity(intent);
                    isFirst = false;
                }

            }
        }).start();
        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        int anHour = 10*1000;
        long triggerAtTime = SystemClock.elapsedRealtime() + anHour;
        Intent i = new Intent(this, AlarmReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
        return super.onStartCommand(intent, flags, startId);
    }

    private Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            boolean run = TbqRuningNow.runNow(CheckAppRunService.this);
            if(!run)
            {
                Log.i("cjj","....reboot....");
                RootCmdUtil.execRootCmdSilent(" reboot ");
            }
            super.handleMessage(msg);
        }
    };
}
